﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Common;
using System.IO;
using SDLITS.Model;
using SDLITS.Common;
using System.ServiceModel.Web;
using System.Security.Cryptography;
using System.Text;
using System.ComponentModel;
using MySoft.Data;
using System.Data.SqlClient;
using System.Data;

namespace SDLITS.Web
{
    #region public
    /// <summary>
    /// 返回实体格式
    /// </summary>
    public class ReturnModel
    {
        public string check { get; set; }
        public string cmd { get; set; }
        public string timestamp { get; set; }
        public string status { get; set; }
        public object result { get; set; }
    }

    /// <summary>
    /// 公用主格式实体
    /// </summary>
    public class MainCheckModel
    {
        public string check { get; set; }
        public string cmd { get; set; }
        public string timestamp { get; set; }
        public object para { get; set; }
    }
    #endregion

    #region userAudit

    public class userAuditReturn
    {
        public string memcardno { get; set; }
        public List<string> mobile { get; set; }
    }

    /// <summary>
    /// 会员实体
    /// </summary>
    public class userAuditPost
    {
        /// <summary>
        /// 会员卡
        /// </summary>
        public string memcardno { get; set; }
        /// <summary>
        /// 会员密码
        /// </summary>
        public string password { get; set; }
        /// <summary>
        /// 会员类型
        /// </summary>
        public string type { get; set; }
        /// <summary>
        /// 会员版本
        /// </summary>
        public string version { get; set; }
        public string deviceid { get; set; }

    }
    #endregion

    #region contactSearch

    public class contactSearchReturn
    {
        /// <summary>
        /// 会员编号 （一卡通卡号）
        /// </summary>
        public string memcardno { get; set; }
        /// <summary>
        /// 会员名称
        /// </summary>
        public string realname { get; set; }
        /// <summary>
        /// 性别，可以为男/女
        /// </summary>
        public string sex { get; set; }
        /// <summary>
        /// 区域，格式为省+区，如“浙江杭州”
        /// </summary>
        public string place { get; set; }
    }

    public class contactSearchPost
    {
        /// <summary>
        /// 会员卡
        /// </summary>
        public string memcardno { get; set; }
        /// <summary>
        /// 会员密码
        /// </summary>
        public string password { get; set; }
        /// <summary>
        /// 搜索的登录名全部（一卡通卡号）
        /// </summary>
        public string destmemcardno { get; set; }
        /// <summary>
        /// 搜索的真实姓名/企业名称全部或部分信息
        /// </summary>
        public string destname { get; set; }
    }
    #endregion

    #region contactGet
    public class contactGetPost
    {
        public string memcardno { get; set; }
        public string password { get; set; }
        public string destmemcardno { get; set; }

    }

    public class contactGetReturn
    {
        public string memcardno { get; set; }
        public string realname { get; set; }
        public string sex { get; set; }
        public string place { get; set; }

    }
    #endregion

    #region goodsQuery
    public class goodsQueryPost
    {
        public string memcardno { get; set; }
        public string password { get; set; }
        public int skipcount { get; set; }
        public int pagesize { get; set; }
        public string fromprovince { get; set; }
        public string fromcity { get; set; }
        public string fromregion { get; set; }
        public string toprovince { get; set; }
        public string tocity { get; set; }
        public string toregion { get; set; }
        public string carlength { get; set; }
        public string carstructrequire { get; set; }
        public string tonmin { get; set; }
        public string tonmax { get; set; }
        public string volmin { get; set; }
        public string volmax { get; set; }

    }

    public class goodsQueryReturn
    {

        public string goodsname { get; set; }
        public string releasedate { get; set; }
        public string fromprovince { get; set; }
        public string fromcity { get; set; }
        public string fromregion { get; set; }
        public string toprovince { get; set; }
        public string tocity { get; set; }
        public string toregion { get; set; }
        public string carlengthrequire { get; set; }
        public string carstructrequire { get; set; }
        public string goodsweight { get; set; }
        public string goodsvolume { get; set; }
        public string ntransmoney { get; set; }
        public string elescreennumber { get; set; }
        public string trademobilenumber { get; set; }
        public string description { get; set; }

    }
    #endregion

    #region reportFeedback
    public class reportFeedbackPost
    {
        public string memcardno { get; set; }
        public string password { get; set; }
        public string feedback { get; set; }

    }

    public class reportFeedbackReturn
    {

    }
    #endregion

    #region reportError
    public class reportErrorPost
    {
        public string memcardno { get; set; }
        public string stacktrace { get; set; }

    }

    public class reportErrorReturn
    {

    }
    #endregion

    #region vehicleQuery
    public class vehicleQueryPost
    {
        public string memcardno { get; set; }
        public string password { get; set; }

    }

    public class vehicleQueryReturn
    {
        public string carplatenumber { get; set; }
        public string caraxle { get; set; }
        public string carstruct { get; set; }
        public string carlong { get; set; }
        public string fromprovince { get; set; }
        public string fromcity { get; set; }
        public string fromregion { get; set; }
        public string toprovince { get; set; }
        public string tocity { get; set; }
        public string toregion { get; set; }
        public string validdate { get; set; }
        public string invaliddate { get; set; }


    }
    #endregion

    #region vehiclePublish
    public class vehiclePublishPost
    {
        public string memcardno { get; set; }
        public string password { get; set; }
        public string carplatenumber { get; set; }
        public string toprovince { get; set; }
        public string tocity { get; set; }
        public string toregion { get; set; }
        public string fromprovince { get; set; }
        public string fromcity { get; set; }
        public string fromregion { get; set; }
        public string validdate { get; set; }
        public string invaliddate { get; set; }
    }

    public class vechiclePublishReturn
    {


    }
    #endregion

    #region accountBalance
    public class accountBalancePost
    {
        public string memcardno { get; set; }
        public string password { get; set; }
    }

    public class accountBalanceReturn
    {
        public string memcardno { get; set; }
        public string amount { get; set; }

    }
    #endregion

    #region accountCharged
    public class accountChargedPost
    {
        public string memcardno { get; set; }
        public string password { get; set; }
        public string startdate { get; set; }
        public string enddate { get; set; }
    }

    public class accountChargedReturn
    {
        public string memcardno { get; set; }
        public string costamount { get; set; }
        public string inputdate { get; set; }
    }
    #endregion

    #region accountHistory
    public class accountHistoryPost
    {
        public string memcardno { get; set; }
        public string password { get; set; }
        public string startdate { get; set; }
        public string enddate { get; set; }
    }

    public class accountHistoryReturn
    {
        public string memcardno { get; set; }
        public string transactionamount { get; set; }
        public string info { get; set; }
        public string date { get; set; }

    }
    #endregion

    #region locationUpdate
    public class locationUpdatePost
    {
        public string deviceid { get; set; }
        public string memcardno { get; set; }
        public int count { get; set; }
        public object[] locationinfo { get; set; }

    }
    public class locationinfo
    {
        public string latitude { get; set; }
        public string longitude { get; set; }
        public string realtime { get; set; }
    }
    public class locationUpdateReturn
    {
        public string memcardno { get; set; }
        public string transactionamount { get; set; }
        public string info { get; set; }
        public string date { get; set; }

    }
    #endregion


    /// <summary>
    /// ApiCheck 的摘要说明
    /// </summary>
    public class ApiCheck : IHttpHandler
    {

        #region HELPER
        public static bool IsUser(string check, string cmd, string timespan)
        {
            string a = GetMD5(cmd + "secret" + timespan, "utf-8");
            if (check == a)
                return true;
            else
                return false;

        }


        /// <summary>
        /// 与ASP兼容的MD5加密算法
        /// </summary>
        public static string GetMD5(string s, string encodingCharset)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] t = md5.ComputeHash(Encoding.GetEncoding(encodingCharset).GetBytes(s));
            StringBuilder sb = new StringBuilder(32);
            for (int i = 0; i < t.Length; i++)
            {
                sb.Append(t[i].ToString("x").PadLeft(2, '0'));
            }
            return sb.ToString();
        }

        #endregion

        /// <summary>
        /// 接收并处理
        /// </summary>
        /// <param name="context"></param>
        public void ProcessRequest(HttpContext context)
        {
            string json = "";
            context.Response.ContentType = "application/json";
            context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            using (var reader = new System.IO.StreamReader(context.Request.InputStream))
            {
                String xmlData = reader.ReadToEnd();
                if (!string.IsNullOrEmpty(xmlData))
                {
                    MainCheckModel checkModel = AnsyModel(xmlData);
                    if (IsUser(checkModel.check, checkModel.cmd, checkModel.timestamp))
                    {
                        switch (checkModel.cmd)
                        {
                            case "userAudit":
                                json = userAudit(checkModel);
                                break;
                            case "contactSearch":
                                json = contactSearch(checkModel);
                                break;
                            case "contactGet":
                                json = contactGet(checkModel);
                                break;
                            case "goodsQuery":
                                json = goodsQuery(checkModel);
                                break;
                            case "reportFeedback":
                                json = reportFeedback(checkModel);
                                break;
                            case "reportError":
                                json = reportError(checkModel);
                                break;
                            case "vehicleQuery":
                                json = vehicleQuery(checkModel);
                                break;
                            case "vehiclePublish":
                                json = vechiclePublish(checkModel);
                                break;
                            case "accountBalance":
                                json = accountBalance(checkModel);
                                break;
                            case "accountCharged":
                                json = accountCharged(checkModel);
                                break;
                            case "accountHistory":
                                json = accountHistory(checkModel);
                                break;
                            case "locationUpdate":
                                json = locationUpdate(checkModel);
                                break;
                            default:
                                break;
                        }
                    }
                    else
                        json = "{\"stutus\":\"403\"}";
                }
            }
            context.Response.ContentType = "text/json;charset=utf-8";
            context.Response.Write(json);
        }


        #region PUBLIC方法
        public MainCheckModel AnsyModel(string json)
        {
            return JsonHelp.JsonDeserialize<MainCheckModel>(json);
        }

        public object setCheckModel<T>(T t, object para)
        {
            Dictionary<string, object> dic = new Dictionary<string, object>();
            foreach (KeyValuePair<string, object> kv in (Dictionary<string, object>)para)
            {
                if (kv.Value != null)
                    if (kv.Key == "locationinfo")
                        dic.Add(kv.Key, kv.Value);
                    else
                        dic.Add(kv.Key, kv.Value);
                else
                    dic.Add(kv.Key, "");
            }

            System.Reflection.PropertyInfo[] properties = t.GetType().GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);

            foreach (System.Reflection.PropertyInfo item in properties)
            {
                if (item.PropertyType.Name == "Int32")
                    item.SetValue(t, int.Parse(dic[item.Name].ToString()));

                else
                    if (item.PropertyType.Name == "List`1")
                        item.SetValue(t, dic[item.Name]);
                    else
                        item.SetValue(t, dic[item.Name]);

            }

            return (object)t;
        }


        #endregion

        #region 会员验证
        /// <summary>
        /// 验证用户
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public string userAudit(MainCheckModel model)
        {
            userAuditPost ca = new userAuditPost();
            ca = (userAuditPost)setCheckModel<userAuditPost>(ca, model.para);
            string json = "";
            string s = UserStatus(ca.memcardno, ca.password);
            ReturnModel rm = new ReturnModel();
            rm.check = model.check;
            rm.cmd = model.cmd;
            rm.timestamp = model.timestamp;
            if (s == "200")
            {
                List<string> ls = new List<string>();
                V_MemCardInfoType mem = SDDbSession.Default.From<V_MemCardInfoType>().Where(V_MemCardInfoType._.MemCardNo == ca.memcardno).ToFirst();
                rm.status = "200";
                userAuditReturn cur = new userAuditReturn();
                cur.memcardno = ca.memcardno;
                ls.Add(mem.Cell);
                ls.Add(mem.Phone);

                cur.mobile = ls;
                rm.result = (object)cur;
                //json = //"{\"status\":\"200\", \"result\":{\"memcardno\":\"" + ca.memcardno + "\",\"mobile\":[\"" + mem.Cell + "\"] }}";
            }
            else if (s == "501")
            {
                rm.status = "501";
                rm.result = null;
            }
            else
            {
                rm.status = "500";
                rm.result = null;
            }
            json = JsonHelp.JsonSerializer<ReturnModel>(rm);
            return json;
        }
        #region 会员
        private string UserStatus(string MemcardNo, string Password)
        {
            V_MemCardInfoType mem = SDDbSession.Default.From<V_MemCardInfoType>().Where(V_MemCardInfoType._.MemCardNo == MemcardNo).ToFirst();
            if (mem != null)
            {
                try
                {
                    string str = mem.IDNumber.Substring(mem.IDNumber.Length - 6);
                    if (GetMD5(str, "utf-8") == Password)
                    {
                        return "200";
                    }
                    else
                    { return "501"; }
                }
                catch (Exception) { return "501"; }
            }
            else
            { return "500"; }
        }
        #endregion
        #endregion

        #region 会员检索
        /// <summary>
        /// 会员检索
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public string contactSearch(MainCheckModel model)
        {
            string json = "";
            ReturnModel rm = new ReturnModel();
            rm.check = model.check;
            rm.cmd = model.cmd;
            rm.timestamp = model.timestamp;
            contactSearchPost ca = new contactSearchPost();
            ca = (contactSearchPost)setCheckModel<contactSearchPost>(ca, model.para);
            string s = UserStatus(ca.memcardno, ca.password);
            if (s == "200")
            {

                WhereClip wc = WhereClip.All;
                if (!string.IsNullOrEmpty(ca.destmemcardno))
                {
                    wc = wc && V_MemCardInfoType._.MemCardNo == ca.destmemcardno;
                }
                if (!string.IsNullOrEmpty(ca.destname))
                {
                    wc = wc && V_MemCardInfoType._.Name.Contain(ca.destname);
                }
                List<V_MemCardInfoType> list = SDDbSession.Default.From<V_MemCardInfoType>().Where(wc).Page(20, 1).ToList();
                List<contactSearchReturn> items = new List<contactSearchReturn>();
                if (list.Count > 0)
                {
                    foreach (var li in list)
                    {
                        contactSearchReturn cs = new contactSearchReturn();
                        cs.memcardno = li.MemCardNo;
                        cs.place = li.IDAddress;
                        cs.realname = li.Name;
                        cs.sex = string.IsNullOrEmpty(li.Sex.ToString()) ? "男" : (Convert.ToBoolean(li.Sex) ? "男" : "女");
                        items.Add(cs);
                    }
                }
                rm.status = "200";
                rm.result = (object)items;
            }
            else
            {
                rm.status = "500";
                rm.result = null;
            }
            json = JsonHelp.JsonSerializer<ReturnModel>(rm);
            return json;
        }

        #endregion

        #region 会员查询接口
        /// <summary>
        /// 会员查询接口
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public string contactGet(MainCheckModel model)
        {
            string json = "";
            ReturnModel rm = new ReturnModel();
            rm.check = model.check;
            rm.cmd = model.cmd;
            rm.timestamp = model.timestamp;
            contactGetPost ca = new contactGetPost();
            ca = (contactGetPost)setCheckModel<contactGetPost>(ca, model.para);
            string s = UserStatus(ca.memcardno, ca.password);
            if (s == "200")
            {
                WhereClip wc = WhereClip.All;
                if (!string.IsNullOrEmpty(ca.destmemcardno))
                {
                    wc = wc && V_MemCardInfoType._.MemCardNo == ca.destmemcardno;
                }
                V_MemCardInfoType list = SDDbSession.Default.From<V_MemCardInfoType>().Where(wc).ToFirst();
                contactGetReturn cs = new contactGetReturn();
                if (list != null)
                {
                    cs.memcardno = list.MemCardNo;
                    cs.place = list.IDAddress;
                    cs.realname = list.Name;
                    cs.sex = string.IsNullOrEmpty(list.Sex.ToString()) ? "男" : (Convert.ToBoolean(list.Sex) ? "男" : "女");
                }
                rm.status = "200";
                rm.result = (object)cs;
            }
            else
            {
                rm.status = "500";
                rm.result = null;
            }
            json = JsonHelp.JsonSerializer<ReturnModel>(rm);
            return json;
        }
        #endregion

        #region 货源查询接口
        /// <summary>
        /// 货源查询接口
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public string goodsQuery(MainCheckModel model)
        {
            string json = "";
            ReturnModel rm = new ReturnModel();
            rm.check = model.check;
            rm.cmd = model.cmd;
            rm.timestamp = model.timestamp;
            goodsQueryPost ca = new goodsQueryPost();
            ca = (goodsQueryPost)setCheckModel<goodsQueryPost>(ca, model.para);
            string s = UserStatus(ca.memcardno, ca.password);
            if (s == "200")
            {
                #region 条件
                WhereClip wc = WhereClip.All;
                if (!string.IsNullOrEmpty(ca.fromprovince))
                {
                    wc = wc && V_LEDMessgeRegion._.StartTopRegionName == ca.fromprovince;
                }
                if (!string.IsNullOrEmpty(ca.fromcity))
                {
                    wc = wc && V_LEDMessgeRegion._.StartParentRegionName == ca.fromcity;
                }
                if (!string.IsNullOrEmpty(ca.fromregion))
                {
                    wc = wc && V_LEDMessgeRegion._.StartRegionName == ca.fromregion;
                }
                if (!string.IsNullOrEmpty(ca.toprovince))
                {
                    wc = wc && V_LEDMessgeRegion._.EndTopRegionName == ca.toprovince;
                }
                if (!string.IsNullOrEmpty(ca.tocity))
                {
                    wc = wc && V_LEDMessgeRegion._.EndParentRegionName == ca.tocity;
                }
                if (!string.IsNullOrEmpty(ca.toregion))
                {
                    wc = wc && V_LEDMessgeRegion._.EndRegionName == ca.toregion;
                }
                if (!string.IsNullOrEmpty(ca.carlength))
                {
                    wc = wc && V_LEDMessgeRegion._.CarInfo == ca.carlength;
                }
                if (!string.IsNullOrEmpty(ca.tonmax))
                {
                    wc = wc && V_LEDMessgeRegion._.Amount <= ca.tonmax && V_LEDMessgeRegion._.UnitType == "吨";
                }
                if (!string.IsNullOrEmpty(ca.tonmin))
                {
                    wc = wc && V_LEDMessgeRegion._.Amount >= ca.tonmin && V_LEDMessgeRegion._.UnitType == "吨";
                }
                if (!string.IsNullOrEmpty(ca.volmax))
                {
                    wc = wc && V_LEDMessgeRegion._.Amount <= ca.volmax && V_LEDMessgeRegion._.UnitType == "立方";
                }
                if (!string.IsNullOrEmpty(ca.volmin))
                {
                    wc = wc && V_LEDMessgeRegion._.Amount >= ca.volmin && V_LEDMessgeRegion._.UnitType == "立方";
                }
                #endregion
                double skip = 0;
                double page = 0;
                skip = double.Parse(ca.skipcount.ToString());
                page = double.Parse(ca.pagesize.ToString());
                List<V_LEDMessgeRegion> list = SDDbSession.Default.From<V_LEDMessgeRegion>().Where(wc).Page(Convert.ToInt32(page), Convert.ToInt32(Math.Floor(skip / page) + 1)).ToList();
                List<goodsQueryReturn> items = new List<goodsQueryReturn>();
                if (list.Count > 0)
                {
                    foreach (var li in list)
                    {
                        goodsQueryReturn cs = new goodsQueryReturn();
                        cs.carlengthrequire = li.CarInfo.ToString();
                        cs.description = "";
                        cs.elescreennumber = li.RoomName;
                        cs.fromcity = li.StartParentRegionName;
                        cs.fromprovince = li.StartTopRegionName;
                        cs.fromregion = li.StartRegionName;
                        cs.goodsname = li.GoodName;
                        cs.goodsvolume = li.Amount.ToString();
                        cs.goodsweight = li.Amount.ToString();
                        cs.ntransmoney = "";
                        cs.releasedate = li.CreateDate.ToString();
                        cs.tocity = li.EndParentRegionName;
                        cs.toprovince = li.EndTopRegionName;
                        cs.toregion = li.EndRegionName;
                        cs.trademobilenumber = "";
                        items.Add(cs);
                    }
                    rm.status = "200";
                    rm.result = (object)items;
                }
                else
                {
                    rm.status = "503";
                    rm.result = null;
                }
            }
            else if (s == "501")
            {
                rm.status = "501";
                rm.result = null;
            }
            else
            {
                rm.status = "500";
                rm.result = null;
            }

            json = JsonHelp.JsonSerializer<ReturnModel>(rm);
            return json;
        }
        #endregion

        #region 提交反馈接口
        /// <summary>
        /// 提交反馈接口
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public string reportFeedback(MainCheckModel model)
        {
            string json = "";
            ReturnModel rm = new ReturnModel();
            rm.check = model.check;
            rm.cmd = model.cmd;
            rm.timestamp = model.timestamp;
            reportFeedbackPost ca = new reportFeedbackPost();
            ca = (reportFeedbackPost)setCheckModel<reportFeedbackPost>(ca, model.para);
            string s = UserStatus(ca.memcardno, ca.password);
            if (s == "200")
            {
                AppFeedback back = new AppFeedback();
                back.DeAttach();
                back.Memcardno = ca.memcardno;
                back.Feedback = ca.feedback;
                back.Addtime = DateTime.Now;
                SDDbSession.Default.Insert(back);
                rm.status = "200";
                rm.result = null;
            }
            else
            {
                rm.status = "500";
                rm.result = null;
            }
            json = JsonHelp.JsonSerializer<ReturnModel>(rm);
            return json;
        }
        #endregion

        #region 提交异常接口
        /// <summary>
        /// 提交异常接口
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public string reportError(MainCheckModel model)
        {
            string json = "";

            ReturnModel rm = new ReturnModel();
            rm.check = model.check;
            rm.cmd = model.cmd;
            rm.timestamp = model.timestamp;
            try
            {
                reportErrorPost ca = new reportErrorPost();
                ca = (reportErrorPost)setCheckModel<reportErrorPost>(ca, model.para);
                AppException back = new AppException();
                back.DeAttach();
                back.Memcardno = ca.memcardno;
                back.Stacktrace = ca.stacktrace;
                back.Addtime = DateTime.Now;
                SDDbSession.Default.Insert(back);
                rm.status = "200";
                rm.result = null;
            }
            catch (Exception ex)
            {
                rm.status = "500";
                rm.result = null;
            }

            json = JsonHelp.JsonSerializer<ReturnModel>(rm);
            return json;
        }
        #endregion

        #region 车辆信息查询接口
        /// <summary>
        /// 车辆信息查询接口
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public string vehicleQuery(MainCheckModel model)
        {
            string json = "";
            ReturnModel rm = new ReturnModel();
            rm.check = model.check;
            rm.cmd = model.cmd;
            rm.timestamp = model.timestamp;
            vehicleQueryPost ca = new vehicleQueryPost();
            ca = (vehicleQueryPost)setCheckModel<vehicleQueryPost>(ca, model.para);
            string s = UserStatus(ca.memcardno, ca.password);
            if (s == "200")
            {
                V_MemCardInfoType vtype = SDDbSession.Default.From<V_MemCardInfoType>().Where(V_MemCardInfoType._.MemCardNo == ca.memcardno).ToFirst();

                List<MemberCarInfo> car = SDDbSession.Default.From<MemberCarInfo>().Where(MemberCarInfo._.Memcardno == ca.memcardno).ToList();
                if (car.Count > 0)
                {
                    List<vehicleQueryReturn> qrt = new List<vehicleQueryReturn>();
                    foreach (MemberCarInfo item in car)
                    {
                        vehicleQueryReturn qr = new vehicleQueryReturn();
                        qr.carplatenumber = item.Carplatenumber;
                        qr.caraxle = "";
                        qr.carlong = "";
                        qr.carstruct = "";
                        qr.fromcity = item.Fromcity;
                        qr.fromprovince = item.Fromprovince;
                        qr.fromregion = item.Fromregion;
                        qr.invaliddate = item.Invaliddate;
                        qr.tocity = item.Tocity;
                        qr.toprovince = item.Toprovince;
                        qr.toregion = item.Toregion;
                        qr.validdate = item.Validdate;
                        qrt.Add(qr);
                    }

                    rm.status = "200";
                    rm.result = (object)qrt;
                }
                else
                {
                    if (vtype != null)
                    {
                        List<vehicleQueryReturn> qrt = new List<vehicleQueryReturn>();

                        vehicleQueryReturn qr = new vehicleQueryReturn();
                        qr.carplatenumber = vtype.CarNo;
                        qr.caraxle = "";
                        qr.carlong = "";
                        qr.carstruct = "";
                        qr.fromcity = "";
                        qr.fromprovince = "";
                        qr.fromregion = "";
                        qr.invaliddate = "";
                        qr.tocity = "";
                        qr.toprovince = "";
                        qr.toregion = "";
                        qr.validdate = "";
                        qrt.Add(qr);

                        rm.status = "200";
                        rm.result = (object)qrt;
                    }
                    else
                    {

                        rm.status = "502";
                        rm.result = null;
                    }
                }

            }
            else if (s == "501")
            {
                rm.status = "501";
                rm.result = null;
            }
            else
            {
                rm.status = "500";
                rm.result = null;
            }
            json = JsonHelp.JsonSerializer<ReturnModel>(rm);
            return json;
        }
        #endregion

        #region 空车发布接口
        /// <summary>
        /// 空车发布接口
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public string vechiclePublish(MainCheckModel model)
        {
            string json = "";
            ReturnModel rm = new ReturnModel();
            rm.check = model.check;
            rm.cmd = model.cmd;
            rm.timestamp = model.timestamp;
            vehiclePublishPost ca = new vehiclePublishPost();
            ca = (vehiclePublishPost)setCheckModel<vehiclePublishPost>(ca, model.para);
            string s = UserStatus(ca.memcardno, ca.password);
            if (s == "200")
            {
                if (ca.validdate == "")
                {
                    SDDbSession.Default.FromSql("delete from MemberCarInfo where Tocity='" + ca.tocity + "' and Toprovince='" + ca.toprovince + "' and  Fromprovince='" + ca.fromprovince + "' and Carplatenumber='" + ca.carplatenumber + "' and Fromcity='" + ca.fromcity + "'").ExecuteNonQuery();
                    rm.status = "200";
                    rm.result = null;
                }
                else
                {
                    MemberCarInfo car = new MemberCarInfo();
                    car.DeAttach();
                    car.Carplatenumber = ca.carplatenumber;
                    car.Fromcity = ca.fromcity;
                    car.Fromprovince = ca.fromprovince;
                    car.Fromregion = ca.fromregion;
                    car.Invaliddate = ca.invaliddate;
                    car.Memcardno = ca.memcardno;
                    car.Tocity = ca.tocity;
                    car.Toprovince = ca.toprovince;
                    car.Toregion = ca.toregion;
                    car.Validdate = ca.validdate;
                    SDDbSession.Default.Insert(car);
                    rm.status = "200";
                    rm.result = null;
                }
            }
            else if (s == "501")
            {
                rm.status = "501";
                rm.result = null;
            }
            else
            {
                rm.status = "500";
                rm.result = null;
            }
            json = JsonHelp.JsonSerializer<ReturnModel>(rm);
            return json;
        }
        #endregion

        #region 一卡通余额接口
        /// <summary>
        /// 一卡通余额接口
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public string accountBalance(MainCheckModel model)
        {
            string json = "";
            ReturnModel rm = new ReturnModel();
            rm.check = model.check;
            rm.cmd = model.cmd;
            rm.timestamp = model.timestamp;
            accountBalancePost ca = new accountBalancePost();
            ca = (accountBalancePost)setCheckModel<accountBalancePost>(ca, model.para);
            string s = UserStatus(ca.memcardno, ca.password);
            if (s == "200")
            {
                V_MemCardInfoType mem = SDDbSession.Default.From<V_MemCardInfoType>().Where(V_MemCardInfoType._.MemCardNo == ca.memcardno).ToFirst();
                if (mem != null)
                {
                    accountBalanceReturn br = new accountBalanceReturn();
                    string str = mem.IDNumber.Substring(mem.IDNumber.Length - 6);
                    if (GetMD5(str, "utf-8") == ca.password)
                    {
                        if (!string.IsNullOrEmpty(mem.LeftCash.ToString()))
                        {
                            string amount = mem.LeftCash.ToString();
                            br.amount = amount;
                            br.memcardno = ca.memcardno;
                        }
                    }
                    rm.status = "200";
                    rm.result = (object)br;
                }
                else
                {
                    rm.status = "502";
                    rm.result = null;
                }

            }
            else if (s == "501")
            {
                rm.status = "501";
                rm.result = null;
            }
            else
            {
                rm.status = "500";
                rm.result = null;
            }
            json = JsonHelp.JsonSerializer<ReturnModel>(rm);
            return json;
        }
        #endregion

        #region 充值查询接口
        /// <summary>
        /// 充值查询接口
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public string accountCharged(MainCheckModel model)
        {
            string json = "";
            ReturnModel rm = new ReturnModel();
            rm.check = model.check;
            rm.cmd = model.cmd;
            rm.timestamp = model.timestamp;
            accountChargedPost ca = new accountChargedPost();
            ca = (accountChargedPost)setCheckModel<accountChargedPost>(ca, model.para);
            string s = UserStatus(ca.memcardno, ca.password);
            if (s == "200")
            {
                SqlParameter[] sp = new SqlParameter[]{
                            new SqlParameter("@CreateUserID",""),
                            new SqlParameter("@MemcardNo",ca.memcardno),
                            new SqlParameter("@StartDate",ca.startdate),
                            new SqlParameter("@EndDate",ca.enddate),
                            new SqlParameter("@SPAction","SelectByDateRange")
                        };
                DataSet ds = SDDbSession.Default.FromProc("TableCardRevenue").AddParameter(sp).ToDataSet();
                List<accountChargedReturn> items = new List<accountChargedReturn>();
                if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        accountChargedReturn ac = new accountChargedReturn();
                        ac.costamount = ds.Tables[0].Rows[i]["PlusAmount"].ToString();
                        ac.inputdate = ds.Tables[0].Rows[i]["CreateDate"].ToString();
                        ac.memcardno = ca.memcardno;
                        items.Add(ac);
                    }
                }
                rm.status = "200";
                rm.result = (object)items;
            }
            else if (s == "501")
            {
                rm.status = "501";
                rm.result = null;
            }
            else
            {
                rm.status = "500";
                rm.result = null;
            }

            json = JsonHelp.JsonSerializer<ReturnModel>(rm);
            return json;
        }

        #endregion

        #region 消费记录查询接口
        /// <summary>
        /// 消费记录查询接口
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public string accountHistory(MainCheckModel model)
        {
            string json = "";
            ReturnModel rm = new ReturnModel();
            rm.check = model.check;
            rm.cmd = model.cmd;
            rm.timestamp = model.timestamp;
            accountHistoryPost ca = new accountHistoryPost();
            ca = (accountHistoryPost)setCheckModel<accountHistoryPost>(ca, model.para);
            string s = UserStatus(ca.memcardno, ca.password);
            if (s == "200")
            {
                WhereClip wc = WhereClip.All;
                if (!string.IsNullOrEmpty(ca.startdate))
                {
                    wc = wc && V_CardExpense._.CreateDate >= ca.startdate;
                }
                if (!string.IsNullOrEmpty(ca.enddate))
                {
                    wc = wc && V_CardExpense._.CreateDate <= ca.enddate;
                }
                List<V_CardExpense> list = SDDbSession.Default.From<V_CardExpense>().Where(wc).Page(20, 1).ToList();
                List<accountHistoryReturn> items = new List<accountHistoryReturn>();
                if (list != null)
                    foreach (var li in list)
                    {
                        accountHistoryReturn ac = new accountHistoryReturn();
                        ac.date = li.CreateDate.ToString();
                        ac.info = li.Value;
                        ac.memcardno = ca.memcardno;
                        ac.transactionamount = li.Amount.ToString();
                        items.Add(ac);
                    }

                rm.status = "200";
                rm.result = (object)items;
            }
            else if (s == "501")
            {
                rm.status = "501";
                rm.result = null;
            }
            else
            {
                rm.status = "500";
                rm.result = null;
            }

            json = JsonHelp.JsonSerializer<ReturnModel>(rm);
            return json;
        }

        #endregion

        #region 位置信息上报接口
        /// <summary>
        /// 位置信息上报接口
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public string locationUpdate(MainCheckModel model)
        {
            string json = "";
            ReturnModel rm = new ReturnModel();
            rm.check = model.check;
            rm.cmd = model.cmd;
            rm.timestamp = model.timestamp;
            locationUpdatePost ca = new locationUpdatePost();
            ca = (locationUpdatePost)setCheckModel<locationUpdatePost>(ca, model.para);
            object[] lists = ca.locationinfo;

            int result = 0;
            if (lists.Count() > 0)
            {
                Dictionary<string, object> dic = new Dictionary<string, object>();
                foreach (object kv in lists)
                {
                    Location item = new Location();
                    dic = (Dictionary<string, object>)kv;
                    foreach (KeyValuePair<string, object> kvt in dic)
                    {
                        if (kvt.Key == "latitude")
                            item.Latitude = kvt.Value.ToString();
                        if (kvt.Key == "longitude")
                            item.Longitude = kvt.Value.ToString();
                        if (kvt.Key == "realtime")
                            item.Realtime = kvt.Value.ToString();
                    }

                    item.DeAttach();
                    item.Deviceid = ca.deviceid;
                    item.Memcardno = ca.memcardno;
                    //item.Latitude = 
                    //item.Longitude = l[1].ToString();
                    //item.Realtime = l[2].ToString();
                    result += SDDbSession.Default.Insert(item);
                }
            }
            rm.status = "200";
            rm.result = null;


            json = JsonHelp.JsonSerializer<ReturnModel>(rm);
            return json;
        }

        #endregion

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}